package tools.invoker;

import java.net.*;
import java.io.*;
import java.util.*;

public class Invoker {


	//declarações iniciais
	private String host;
	private StringBuffer msg;
	private int port;
	private Socket connection;
	private ServerSocket socket1;
	InetAddress address;
	private int letra;
	BufferedOutputStream bos;
	OutputStreamWriter osw;
	BufferedInputStream is;
	InputStreamReader isr; 
 
	public Invoker(String host, int port) {
		this.host = host;
		this.port = port;
	}

	public void openConnectionClient() {
		// Open a new connection:
		try {
			address = InetAddress.getByName(host);
			connection = new Socket(address, port);
			bos = new BufferedOutputStream(connection.getOutputStream());
			osw = new OutputStreamWriter(bos,"US-ASCII");
			is = new BufferedInputStream(connection.getInputStream());
			isr = new InputStreamReader(is);


		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void openConnectionServer() {
		// Open a new connection:
		try {
			socket1 = new ServerSocket(port);

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void serverProximo() {
		// Open a new connection:
		try {
			this.connection = socket1.accept();
			bos = new BufferedOutputStream(connection.getOutputStream());
			osw = new OutputStreamWriter(bos,"US-ASCII");
			is = new BufferedInputStream(connection.getInputStream());
			isr = new InputStreamReader(is);

		} catch (Exception e) {
			e.printStackTrace();
		}
	}



	public void closeConnection() {
		// Close the connection:
		try {
			osw.flush();
			connection.close();
			osw.close();
			isr.close();

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void escreve(String envio){

		try {

			osw.write(envio + '&');
			osw.flush();
		} catch ( Exception e ){
			e.printStackTrace();
		}
	}

	public void recebe(){

		try {
			msg = new StringBuffer();

			while(( letra = isr.read()) != '&') {
				msg.append((char)letra);
			}
			System.out.println(msg);
		} catch ( Exception e ){
			e.printStackTrace();
		}	
	}
	

	public String getMsg(){
		return msg.toString();
	}

}
